<template>        
    <div class="session-window">
        <div class="session-window-wrapper">
            <div class="header-part">
                <div class="header-part-img">
                    <el-image style="width: 40px; height: 40px" :src="store.state.userInfo.avatar" />
                </div>
                <div class="header-part-info">

                    <div class="name">
                        <span>
                            {{ store.state.userInfo.username }}
                        </span> 
                    </div>
                    <div class="detail">
                        <span>
                            {{ store.state.userInfo.account }}
                        </span>
                    </div>

                </div>
                <div class="header-part-func">

                    <div class="func-vedio" @click="startVedio">
                        <el-button :icon="Microphone" circle />
                    </div>
                    <div class="func-call">
                        <el-button :icon="VideoCamera" circle />
                    </div>
                    <div class="func-other">
                        <el-button  :icon="Picture" circle />
                    </div>

                </div>
            </div>

            <div class="content-part">

                <div class="content-part-list" ref="chatContent">
                    <div class="message-list" v-for="msgInfo in messageList" key="message.Id">
                        <messageCard :messageInfo="msgInfo"></messageCard>
                    </div>

                </div>

                <div class="content-part-input">

                    <div class="func-tool-part">

                        <!-- emoji表情按钮 -->
                        <div class="emoji-button" @click="showEmojiDialog=true">
                            <!-- <el-icon><PictureRounded /></el-icon> -->
                            <el-image :src="smileImg"></el-image>
                        </div>
                        <!-- 上传文件 -->
                        <div class="pic-button">
                            
                            <el-upload
                                :action="uploadImgUrl"
                                :limit="1"
                                class="img-uploader"
                                :on-exceed="handleExceed"
                                :on-success="uploadImgSuccess"
                                :on-error="uploadImgError"
                                :on-change="handleChange"
                                :before-upload="beforeUploadImg"
                                ref="fileUpload"
                            >
                                <template #trigger>
                                    <el-image :src="picImg"></el-image>
                                </template>


                            </el-upload>

                        </div>

                            
                    </div>

                    <div class="input-part">

                        <el-input

                            v-model="inputTextArea"
                            :rows = "4"
                            type="textarea"
                            pleacholder="xxxx"
                            resize="none"
                             maxlength="200"
                            @keyup.enter.native="enterEvent($event)"
                        >
                        </el-input>

                    </div>

                    <div class="commit-button" @click="sendMsg">
                        <el-text class="mx-1"><span>发送</span></el-text>
                    </div>

                    <el-dialog
                        v-model="showEmojiDialog"
                        title="可可爱爱表情"
                    >   
                        <div class="el-dailog-wrapper">
                            <div v-for="url in emojiUrlList">
                                <EmojiCard :emojiSrc="url" @chooseEmoji="chooseEmojiFunc" @closeDialog="closeDialogFunc"></EmojiCard>
                            </div>
                        </div>
                      
                    </el-dialog>

                </div>

            </div>
        </div>

        <div class="video-dialog" v-if="videoDialog">
            <el-dialog 
                v-model="videoDialog" 
                title="hello world" 
                width="500"
                center
                destroy-on-close
            >
            </el-dialog>
        </div>
    </div>
</template>

<script setup>
import {ref,reactive,onMounted, shallowRef, nextTick,watch, toRefs} from 'vue'
import { useRoute } from 'vue-router'
import { Edit,Check,Star,Microphone,VideoCamera,Picture,PictureRounded} from '@element-plus/icons-vue'
import messageCard from '../components/MessageCard.vue'
import EmojiCard from '../components/EmojiCard.vue'
import '@wangeditor/editor/dist/css/style.css'
import { useStore } from 'vuex'
import smileImg from "../assets/img/hello.png"
import picImg from "../assets/img/pic.png"
// 使用websocket,封装在src/hooks/websocket.js中
// import {useWebScoket} from '../hooks/index'
// ========== 引入requestApi ==========
import { getHistoryMessage } from '../api/userApi'
const router = useRoute()
const messageList = ref([])
// router.query.data 获取参数
const inputTextArea = ref("")
// emoji表情弹窗
const showEmojiDialog = ref(false)
// 富文本编辑器
const editorRef = shallowRef()
const mode = ref('default')
const fileList = ref([])
// 使用存储对象
const store = useStore()
// 监听父组件ref对象的值变化
const props = defineProps({
    newMessage:{}
})

// 获取用户信息
const uid = store.state.userInfo.userId
const avatar = store.state.userInfo.avatar
const username = store.state.userInfo.username
// get字符串会自动将int类型转为str类型,这里需要转回去
const receiveId = parseInt(router.query.uid) 
// ===================================================== 监听父组件ChatRoom =====================================================

/**
 * 父组件ChatRoom,监听ws的消息后,会将新的消息存入一个reactive对象中,如有对象有新值
 * 子组件监听组件是否有值变化,如果有,判断是否id是否属于自己,是自己的话,插入messageList中,不是的话不处理
 * 
 * 
 * **/ 

watch(()=>props.newMessage,(newValue,oldValue)=>{
    console.log("sessionwindows监听到新的新值为:",newValue)
    // ================= 增加判断查看是聊天消息还是信令交换消息逻辑  =================
    if(newValue.receiveId === store.state.userId){
        // 字符串转对象
        if(typeof newValue === 'string'){
            const formatNewValue = JSON.parse(newValue)
            // 交换信令消息
            if(formatNewValue.MsgType == 7 || formatNewValue.MsgType == 8){
                handleViedeoOfferMsg(formatNewValue)
            }else{
                messageList.value.push(JSON.parse(newValue))
            }
            
            // messageList.value.push(JSON.parse(newValue))
        }else{
            messageList.value.push(newValue)
        }
        
        console.log("sessionwindows---监听到新的messageList:",messageList.value);
        scrollToBootom()
    }
})

// ===================================================== mounted方法 =====================================================
// 定时任务模拟发送信息
onMounted(()=>{
    // 获取用户离线消息
    const params = {"rUserId":store.state.userInfo.userId,"sUserId":receiveId}
    getHistoryMessage(params).then(res=>{

        console.log("发送方",receiveId);
        console.log("接收方",store.state.userInfo.userId);
        console.log("离线消息为",res);
        if(res.length != 0){
            for(var i=0;i<res.length; i++){
                messageList.value.push(res[i])
            }
        }

    }).catch(err=>{
        console.log("获取离线消息错误",err);
    })
    scrollToBootom()

})



// ===================================================== 实现滚动框滚动到底部 =====================================================
// 用来判断是否是用于点击
const isScrolling = ref(false)
// 元素绑定ref属性，可通过ref操作元素
const chatContent = ref(null)
// 封装一个滚动滚动至最下方的方法
const scrollToBootom = ()=> {
    nextTick(()=>{
        if(!isScrolling.value) {
            chatContent.value.scrollTop = chatContent.value.scrollHeight - chatContent.value.offsetHeight
        }
    })
}


// ===================================================== 实现发送文字消息 =====================================================
// 发送文字消息
const sendMsg = ()=>{
    // 从store中获取ws对象
    const ws = store.state.ws
    console.log("seesionwindow-进入发送文本消息逻辑")
    if(inputTextArea.value !=""){
        // 消息列表增加发送的消息
        const message = {
            SenderId:uid,
            ReceiveId:receiveId,
            Text:inputTextArea.value,
            SenderImgUrl:avatar,
            SenderShortName:username,
            EmojiUrl:"",
            MsgType :1,
        }
        messageList.value.push(message)
        // 调用websocket发送给服务器
        ws.send(JSON.stringify(message))
        console.log("seesionwindow-进入发消息是:",message)
        inputTextArea.value = ""
    }
    scrollToBootom()
}

// 定义emoji表情列表
const emojiUrlList = ref([
    "/src/components/icons/gft/1.gif",
    "/src/components/icons/gft/2.gif",
    "/src/components/icons/gft/3.gif",
    "/src/components/icons/gft/4.gif",
    "/src/components/icons/gft/5.gif",
    "/src/components/icons/gft/6.gif",
    "/src/components/icons/gft/7.gif",
    "/src/components/icons/gft/8.gif",
    "/src/components/icons/gft/9.gif",
    "/src/components/icons/gft/10.gif",
    "/src/components/icons/gft/11.gif",
    "/src/components/icons/gft/12.gif",
    "/src/components/icons/gft/13.gif",
    "/src/components/icons/gft/14.gif",
    "/src/components/icons/gft/15.gif",
    "/src/components/icons/gft/16.gif",
])




// ===================================================== 实现发送emoji消息 =====================================================
// 发送emoj表情
const sendEmojMsg = (url)=> {
    const ws = store.state.ws
    console.log("seesionwindow-进入发送emoj消息逻辑", url)
    const message = {
        SenderId:uid,
        ReceiveId:receiveId,
        Text:"",
        SenderImgUrl:avatar,
        SenderShortName:username,
        EmojiUrl:url,
        MsgType :2,
    }
    messageList.value.push(message)
    ws.send(JSON.stringify(message))
    // 发送信息时,如有滚动条,自动滚动到最下方
    scrollToBootom()
}



// ===================================================== 实现发送图片消息 =====================================================
const uploadImgUrl = ref("/api/file/upload")
const returnImgUrl = ref("")
const fileUpload = ref(null)
const uploadImgSuccess = (response, file)=> {
    console.log("上传成功");
    console.log(response, file);
    returnImgUrl.value = "http://127.0.0.1:8890/api/static/" + response.data
    const ws = store.state.ws
    const message = {
        SenderId:uid,
        ReceiveId:receiveId,
        Text:returnImgUrl.value,
        SenderImgUrl:avatar,
        SenderShortName:username,
        EmojiUrl:"",
        MsgType :3,
    }
    // 发送图片逻辑
    messageList.value.push(message)
    ws.send(JSON.stringify(message))
    scrollToBootom()
    // 清空流文件,否则多次上传无响应
    fileUpload.value.clearFiles()
}

const uploadImgError = ()=> {
    console.log("上传失败");
}

const beforeUploadImg = (rawFile) => {
    console.log("上传的文件格式为:",rawFile.type)
    if (rawFile.type !== 'image/jpeg' && rawFile.type !=='image/png') {
        ElMessage.error('头像格式必须是:JPG或PNG格式!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('头像大小不能超过2MB!')
        return false
    }
    return true
}
// 发送图片
const sendEmojiMsg = () => {

}

// 上传图片
const uploadImg = () => {
    console.log("上传图片调用此方法");

}

// =============================================== 发送视频逻辑 ===============================================
// 待实现原理同图片


//=============================================== 子组件选中emoJi表情后,触发发送函数 ===============================================
// 子组件EmojiCard调用父组件的方法
const chooseEmojiFunc = (url)=>{
    sendEmojMsg(url) 
}

const closeDialogFunc = (flag)=>{
    showEmojiDialog.value = false
}

//=============================================== 测试视频通话 ====================================
// 又有了实现的可能性
const startVedio = ()=> {
    alert("视频通话")
}

const rtcPeerConnect = ref(null)

// 处理信令交换逻辑
async function handleVideoOfferMsg(msg) {
    // 
    const targetUserId = msg.SenderId
    const targetUsername = msg.Sendershortname
    console.log("sendershortnam:", targetUsername);
    // 未进行rtc连接
    if(!rtcPeerConnect){
        createPeerConnection()
    }
}

async function createPeerConnection(){
    //
    console.log("setting up a rtc connnect");
    rtcPeerConnect = new RTCPeerConnection({
        iceServers:[
            {
                urls:"turn:numb.viagenie.ca" + "",
                username:"webrtc",
                credential:"turnserver"
            }
        ]
    })
}


</script>

<style scoped lang="scss">

.session-window {
    height: 100%;
    width: 100%;
    background-color: #FFFFFF;
    .session-window-wrapper {
        height: 100%;
        .header-part {
            height: 10%;
            background-color:#f9f9f9;
            width: 100%;
            // 通俗解释一下clear:both清除浮动就是，一个大对象内有2个小对象使用了css float样式为了避免产生浮动，
            // 大对象背景或边框不能正确显示，这个时候就需要clear:both清除浮动。
            &::after {
                content: "";
                display: block;
                clear: both;
            }
            position: sticky;
            .header-part-img {
                float: left;
                margin-left: 20px;
                margin-top: 10px;
                // background-color: rebeccapurple;
                height: 60px;
                ::v-deep .el-image {
                    margin-top: 10px;
                }
            }
            .header-part-info {
                float: left;
                margin-top: 15px;
                margin-left: 15px;
                // background-color: yellowgreen;
                height: 60px;
                display: flex;
                flex-direction: column;
                align-content: space-around;
                padding-top: 4.9px;
                .name {
                    span {
                        font-family: "Alibaba_PuHuiTi_2.0_65_Medium_65_Medium";
                        letter-spacing: 0.3px;
                        font-size:14px;
                        color: #212121;
                    }
                }
                .detail {
                    span{
                        font-size:12px;
                        // color: #FFFFFF;
                        font-family: "Alibaba_PuHuiTi_2.0_65_Medium_65_Medium";
                        letter-spacing: 0.3px;
                        color: #212121;
                    }
                }
            }
            .header-part-func {
                float: right;
                display: flex;
                margin-top: 15px;
                margin-right: 15px;
                .func-vedio,.func-call,.func-other {
                    height: 60px;
                    vertical-align:middle;
                    // background-color: aquamarine;
                    margin-bottom: 5px;
                    line-height: 100%;
                    .el-button {
                        margin-top: 14px;
                        margin-left: 5px;
                    }
                }
                .func-other {
                    .el-button {
                        margin-right: 5px;
                    }
                    
                }

            }
        }
        .content-part {
            height: 90%;
            width: 100%;
            .content-part-list {
                height: 78%;
                overflow: auto;
                background-color: #ffffff;
                width: 100%;
                // 修改滑动条样式
                &::-webkit-scrollbar {
                    width: 0;
                    height: 0;
                    display: none;
                }
            }

            .content-part-input {
                background-color:  #f9f9f9;
                height: 22%;
                .commit-button {
                    float:right;
                    margin-top: 5px;
                    margin-right: 10px;
                    span{
                        font-family: "Alibaba_PuHuiTi_2.0_65_Medium_65_Medium";
                        letter-spacing: 0.3px;
                        font-weight: bold;
                        color: #212121;
                    }
                }
                .func-tool-part{

                    display: flex;
                    .emoji-button{
                        width: 30px;
                        height: 30px;
                        // background-color: red;
                        ::v-deep .el-image {
                            margin-left: 7.5px;
                            margin-top: 4.5px;
                        }
                    }
                    .pic-button{
                        width: 30px;
                        height: 30px;
                        // background-color: red;
                        ::v-deep .el-image {
                            margin-left: 7.5px;
                            margin-top: 4.5px;
                        }
                        margin-left: 10px;
                    }
                }
                .el-dailog-wrapper {
                    display: grid;
                    grid-template-columns: 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr ;
                }
                ::v-deep .el-dialog {
                    position: absolute;
                    left:470px;
                    top:520px;
                    width:40%;
                    height: 20%;
                    overflow: auto;

                }
            }
        }
    }       
   
}

</style>